package socket;

import java.io.*;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;

public class Client1 {
    private Socket socket;
    public Client1(){
        try {
            System.out.println("正在连接服务端");
            socket = new Socket("172.40.133.123",8088);
            System.out.println("服务端连接完毕");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    /**
     * 该方法用于启动客户端程序的执行
     */
    public void start(){
        try {
            //启动一个线程，该线程用于接受服务端发送过来的消息
            ServerHandler handler = new ServerHandler();
            Thread t = new Thread(handler);
            t.start();

            //获取一个输出流，向服务端发送消息
            OutputStream out = socket.getOutputStream();
            OutputStreamWriter osw = new OutputStreamWriter(out, StandardCharsets.UTF_8);
            BufferedWriter bw = new BufferedWriter(osw);
            PrintWriter pw = new PrintWriter(bw,true);//自动行刷新

            Scanner scan = new Scanner(System.in);

            while(true){
                System.out.println("请输入昵称：");
                String nickName = scan.nextLine();
                if (nickName.trim().isEmpty()){
                    System.out.println("昵称不能为空！");
                }else {
                    pw.println(nickName);
                    break;

                }
            }

            while (true){
                String line = scan.nextLine();
                if("exit".equalsIgnoreCase(line)){
                    break;
                }
                pw.println(line);//发送数据到服务端
            }

        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

    public static void main(String[] args) {
        Client1 client = new Client1();
        client.start();
    }

    //该线程用于接受服务端发送过来的消息
    private  class ServerHandler implements Runnable{
        public void run(){
            try {
                InputStream in = socket.getInputStream();
                InputStreamReader isr = new InputStreamReader(in, StandardCharsets.UTF_8);
                BufferedReader br = new BufferedReader(isr);

                String message;
                while ((message=br.readLine())!=null){
                    System.out.println(message);
                }
            } catch (IOException e) {
            }
        }
    }
}
